#ifndef __CALC_MEM_SYS_H
#define __CALC_MEM_SYS_H

#pragma pack(push,1)

//mem struct
// Buf====Sp=>.....<=Ep====StaticP====BufE

typedef struct _MS_GRAIN
{
	struct _MS_GRAIN *pNext;
}MS_GRAIN;

#ifndef _MEM_ITEM
#define _MEM_ITEM			\
int nMemSize;		\
unsigned char *pMemBuf; \
unsigned char *pMemSp;	\
unsigned char *pMemEp; \
unsigned char *pStaticP
#endif

typedef struct _MS_DATA
{
	_MEM_ITEM;
}MS_DATA;

#pragma pack(pop)

#ifdef _DEBUG
#define OnMemOut()				OnMemOut_MS();
void OnMemOut_MS();
#else
#define OnMemOut()
#endif

#ifndef MallocMemS
#define MallocMemS(pMemGrain,nGrainSize,GrainType,pLib,OnMemOutCode){	\
	pMemGrain=(GrainType*)((pLib)->pMemSp);	\
	unsigned char *_pSp = ((unsigned char*)(pMemGrain)) + nGrainSize;	\
	if (_pSp <= (pLib)->pMemEp)	\
		(pLib)->pMemSp = _pSp;	\
	else{\
		OnMemOut();\
		OnMemOutCode;\
	}\
}
#endif

#ifndef FreeMemS
#define FreeMemS(pLib){	\
	(pLib)->pMemSp = (pLib)->pMemBuf;	\
}
#endif

#ifndef StoreMemSp
#define StoreMemSp(p,Type,pLib)	\
	p=(Type*)((pLib)->pMemSp);
#endif

#ifndef RestoreMemSp
#define RestoreMemSp(p,pLib)	\
	((pLib)->pMemSp)=(unsigned char*)(p);
#endif

#ifndef MallocMemE
#define MallocMemE(pMemGrain,nGrainSize,GrainType,pLib,OnMemOutCode){\
	pMemGrain = (GrainType*)((pLib)->pMemEp - nGrainSize);\
	if ((unsigned char*)(pMemGrain) >= (pLib)->pMemSp)\
		(pLib)->pMemEp = (unsigned char*)(pMemGrain);\
	else{\
		OnMemOut();\
		OnMemOutCode;\
	}\
}
#endif

#ifndef FreeMemE
#define FreeMemE(pLib){\
	(pLib)->pMemEp = (pLib)->pStaticP;\
}
#endif

#ifndef StoreMemEp
#define StoreMemEp(p,Type,pLib)	\
	p=(Type*)((pLib)->pMemEp);
#endif

#ifndef RestoreMemEp
#define RestoreMemEp(p,pLib)	\
	((pLib)->pMemEp)=(unsigned char*)(p);
#endif

#ifndef FreeMemSE
#define FreeMemSE(pLib){\
	FreeMemS(pLib);\
	FreeMemE(pLib);\
}
#endif


#ifndef MallocStaticMem
#define MallocStaticMem(pMemBuffer,nMemSize,MemType,pLib,OnMemOutCode){\
	pMemBuffer = (MemType*)((pLib)->pStaticP - (int)(nMemSize));\
	if ((unsigned char*)(pMemBuffer) >= (pLib)->pMemSp){\
		(pLib)->pStaticP=(unsigned char*)pMemBuffer;\
		FreeMemE(pLib);\
	}\
	else{\
		OnMemOut();\
		OnMemOutCode;\
	}\
}
#endif

#ifndef FreeLibMem
#define FreeLibMem(pLib){\
	(pLib)->pStaticP = (pLib)->pMemBuf + (pLib)->nMemSize;\
	FreeMemSE(pLib);\
}
#endif

#ifndef InitCalcMemSys
#define InitCalcMemSys(pMem,nSize,pLib){\
(pLib)->nMemSize = (nSize);	\
(pLib)->pMemBuf = (unsigned char*)(pMem);	\
FreeLibMem(pLib);	\
}
#endif

void _CopyCalcMem(unsigned char *pDest, unsigned char *pSrc, int nMemSize);
#define CopyCalcMem(pDest,pSrc,nMemSize)	\
	_CopyCalcMem((unsigned char*)(pDest),(unsigned char*)(pSrc),nMemSize)

int GetCalcMemUse(MS_DATA *pLib);


#endif
	
	